import { EntityManager, MikroORM, knex } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import  randomString from 'string-random'
import { PersonalAccessTokens } from "@entities/PersonalAccessTokens";
import { Users } from "@entities/Users";
import CryptoJS from 'crypto-js'

@Injectable()
export class TokenService {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager
    ){}

    async createToken(user : Users)
    {
        let token = new PersonalAccessTokens();
        const plainTextToken = randomString(40);

        token.abilities = JSON.stringify(user.roles)
        token.token = CryptoJS.SHA256(plainTextToken).toString()
        token.name = 'zp-token'
        token.tokenableType = 'App\\Models\\User'
        token.tokenableId = user.id
        token.createdAt = new Date();
        token.updatedAt = new Date();
    
        await this.em.persistAndFlush(this.em.create(PersonalAccessTokens,token))
        
        const tokenText = `${token.id}|${plainTextToken}`

        return tokenText
    }
}
